package com.paas.form.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.paas.common.model.BaseUserInfo;
import com.paas.common.model.RestResponse;
import com.paas.common.util.BeanUtil;
import com.paas.common.util.StringUtil;
import com.paas.common.web.SystemConst;
import com.paas.common.web.annotion.OperLog;
import com.paas.common.web.controller.BaseController;
import com.paas.common.web.oper.OprLogConstant;
import com.paas.form.entity.*;
import com.paas.form.service.*;
import com.paas.form.vo.FormTaskVo;
import com.paas.form.vo.RuleModelVo;
import com.publics.entity.UcUserEntity;
import com.publics.feign.service.IUcUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/form/formTask")
@Api(description = "form", tags = "")
public class FormTaskController extends BaseController {

    @Autowired
    public IFormTaskService formTaskService;

    @Autowired
    public IFormTaskParamsService formTaskParamsService;

    @Autowired
    public IFormTaskMapperService formTaskMapperService;

    @Autowired
    public IFormModelService formModelService;

    @Autowired
    public IFormModelParamsService formModelParamsService;

    @Autowired
    public IFormViewPubService formViewPubService;

    @Autowired
    public IUcUserService ucUserService;

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(value = "保存信息", notes = "保存信息")
    @OperLog(operType = OprLogConstant.ADD, operModul = "", operDescribe = "-保存")
    public void save(@RequestBody FormTaskEntity formTaskEntity) throws ParseException {
        if (BeanUtil.isNotEmpty(formTaskEntity)) {
            injectUpdateDataAuth(formTaskEntity);
        }
        formTaskService.save(formTaskEntity);
    }


    @RequestMapping(value = "/saveTask", method = RequestMethod.POST)
    @ApiOperation(value = "保存信息", notes = "保存信息")
    @OperLog(operType = OprLogConstant.ADD, operModul = "", operDescribe = "-保存")
    public RestResponse save(@RequestBody FormTaskVo formTaskVo) throws ParseException {
        if (BeanUtil.isNotEmpty(formTaskVo)) {
            // 当前登录人信息
            BaseUserInfo baseUserInfo = getUserInfo();
            // 任务信息
            FormTaskEntity task = formTaskVo.getTask();
            if (BeanUtil.isNotEmpty(task)) {
                task.setModifyId(baseUserInfo.getUserId());
                task.setModifyDate(new Date());
                task.setStatus(SystemConst.NORMAL_STATUS);
                task.setOrgId(baseUserInfo.getOrgId());
                task.setAppId(baseUserInfo.getAppId());
                formTaskService.save(task);
                // 判断任务id是否存在
                if (StringUtil.isNotEmpty(task.getId())) {
                    // 任务参数-删除
                    LambdaQueryWrapper<FormTaskParamsEntity> taskParamsWrapper = new LambdaQueryWrapper<FormTaskParamsEntity>();
                    taskParamsWrapper.eq(FormTaskParamsEntity::getTaskId, task.getId());
                    formTaskParamsService.remove(taskParamsWrapper);
                    //  任务参数-保存
                    List<FormTaskParamsEntity> taskParamsList = formTaskVo.getTaskParamsList();
                    if (BeanUtil.isNotEmpty(taskParamsList) && taskParamsList.size() > 0) {
                        for (FormTaskParamsEntity formTaskParamsEntity : taskParamsList) {
                            formTaskParamsEntity.setTaskId(task.getId());
                            formTaskParamsEntity.setModifyId(baseUserInfo.getUserId());
                            formTaskParamsEntity.setAppId(baseUserInfo.getAppId());
                            formTaskParamsEntity.setStatus(SystemConst.NORMAL_STATUS);
                            formTaskParamsEntity.setModifyDate(new Date());
                        }
                        formTaskParamsService.saveBatch(taskParamsList);
                    }
                    // 任务字段映射-删除
                    LambdaQueryWrapper<FormTaskMapperEntity> taskMapperWrapper = new LambdaQueryWrapper<FormTaskMapperEntity>();
                    taskMapperWrapper.eq(FormTaskMapperEntity::getTaskId, task.getId());
                    formTaskMapperService.remove(taskMapperWrapper);
                    //  任务字段映射-保存
                    List<FormTaskMapperEntity> taskMapperList = formTaskVo.getTaskMapperList();
                    if (BeanUtil.isNotEmpty(taskMapperList) && taskMapperList.size() > 0) {
                        for (FormTaskMapperEntity formTaskMapperEntity : taskMapperList) {
                            formTaskMapperEntity.setTaskId(task.getId());
                            formTaskMapperEntity.setModifyId(baseUserInfo.getUserId());
                            formTaskMapperEntity.setAppId(baseUserInfo.getAppId());
                            formTaskMapperEntity.setModifyDate(new Date());
                            formTaskMapperEntity.setStatus(SystemConst.NORMAL_STATUS);
                        }
                        formTaskMapperService.saveBatch(taskMapperList);
                    }
                }
                return RestResponse.success();
            }
        }
        return RestResponse.error();
    }


    @RequestMapping(value = "/getTaskById", method = RequestMethod.GET)
    @ApiOperation(value = "根据Id查询对象", notes = "根据Id查询对象")
    public FormTaskVo getTaskById(String id) {
        FormTaskVo formTaskVo = null;
        if (StringUtil.isNotEmpty(id)) {
            // 任务信息
            FormTaskEntity task = formTaskService.getById(id);
            if (BeanUtil.isNotEmpty(task)) {
                Map<String, FormModelParamsEntity> modelParamsMap = new HashMap<String, FormModelParamsEntity>();
                // 规则模型信息综合实体
                RuleModelVo ruleModelVo = new RuleModelVo();
                if (StringUtil.isNotEmpty(task.getModelId())) {
                    FormModelEntity formModelEntity = formModelService.getById(task.getModelId());
                    if (BeanUtil.isNotEmpty(formModelEntity)) {
                        // 模型名称-填充
                        task.setModelName(formModelEntity.getModeName());
                        // 规则模型参数信息集合-根据规则模型id
                        FormModelParamsEntity formModelParamsEntity = new FormModelParamsEntity();
                        formModelParamsEntity.setModelId(task.getModelId());
                        formModelParamsEntity.setStatus(SystemConst.NORMAL_STATUS);
                        List<FormModelParamsEntity> modelParamsList = formModelParamsService.getList(formModelParamsEntity);
                        // 规则模型集合转map
                        modelParamsMap = modelParamsList.stream().collect(Collectors.toMap(FormModelParamsEntity::getId, item -> item));
                        // 规则模型信息-填充
                        ruleModelVo.setFormModelEntity(formModelEntity);
                        ruleModelVo.setParamsList(modelParamsList);
                    }
                }
                // 视图信息
                if (StringUtil.isNotEmpty(task.getViewId())) {
                    FormViewPubEntity formViewPubEntity = formViewPubService.getById(task.getViewId());
                    // 视图名称-填充
                    if (BeanUtil.isNotEmpty(formViewPubEntity)) {
                        task.setViewName(formViewPubEntity.getName());
                    }
                }
                // 任务参数信息
                FormTaskParamsEntity formTaskParamsEntity = new FormTaskParamsEntity();
                formTaskParamsEntity.setTaskId(id);
                formTaskParamsEntity.setStatus(SystemConst.NORMAL_STATUS);
                List<FormTaskParamsEntity> taskParamsList = formTaskParamsService.getList(formTaskParamsEntity);
                for (FormTaskParamsEntity taskParamsEntity : taskParamsList) {
                    if (modelParamsMap.containsKey(taskParamsEntity.getParamsId())) {
                        FormModelParamsEntity formModelParamsEntity = modelParamsMap.get(taskParamsEntity.getParamsId());
                        taskParamsEntity.setParamsName(formModelParamsEntity.getCode());
                        taskParamsEntity.setDataType(formModelParamsEntity.getDataType());
                    }
                }
                // 任务映射字段信息
                FormTaskMapperEntity formTaskMapperEntity = new FormTaskMapperEntity();
                formTaskMapperEntity.setTaskId(id);
                formTaskMapperEntity.setStatus(SystemConst.NORMAL_STATUS);
                List<FormTaskMapperEntity> taskMapperList = formTaskMapperService.getList(formTaskMapperEntity);
                // 任务信息-填充
                formTaskVo = new FormTaskVo();
                formTaskVo.setTask(task);
                formTaskVo.setTaskParamsList(taskParamsList);
                formTaskVo.setTaskMapperList(taskMapperList);
                formTaskVo.setRuleModelVo(ruleModelVo);
            }
        }
        return formTaskVo;
    }

    @RequestMapping(value = "/saveBatch", method = RequestMethod.POST)
    @ApiOperation(value = "批量保存信息", notes = "批量保存信息")
    @OperLog(operType = OprLogConstant.UPDATE, operModul = "", operDescribe = "-批量保存修改")
    public void saveBatch(@RequestBody List<FormTaskEntity> list) throws ParseException {
        if (list != null && list.size() > 0) {
            injectUpdateDataAuth(list);
        }
        formTaskService.saveBatch(list);
    }

    @RequestMapping(value = "/deleteById", method = RequestMethod.GET)
    @ApiOperation(value = "根据Id删除数据", notes = "根据Id删除数据")
    @OperLog(operType = OprLogConstant.DELETE, operModul = "", operDescribe = "-删除")
    public void deleteById(String id) {
        if (null != id && !"".equals(id)) {
            FormTaskEntity formTaskEntity = new FormTaskEntity();
            injectUpdateDataAuth(formTaskEntity);
            formTaskEntity.setId(id);
            formTaskService.deleteByEntity(formTaskEntity);
        }
    }

    @RequestMapping(value = "/deleteBatchByIds", method = RequestMethod.POST)
    @ApiOperation(value = "根据Id批量删除数据", notes = "根据Id批量删除数据")
    @OperLog(operType = OprLogConstant.DELETE, operModul = "", operDescribe = "-批量删除")
    public void deleteBatchByIds(@RequestBody List<String> ids) {
        if (null != ids && ids.size() > 0) {
            FormTaskEntity formTaskEntity = new FormTaskEntity();
            injectUpdateDataAuth(formTaskEntity);
            //formTaskService.deleteBatchIds(ids);
            formTaskService.deleteBatchIdsWithPermission(ids, formTaskEntity);
        }
    }

    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    @ApiOperation(value = "根据Id查询对象", notes = "根据Id查询对象")
    public FormTaskEntity queryById(String id) {
        FormTaskEntity bean = formTaskService.getById(id);
        return bean;
    }

    @RequestMapping(value = "/queryBatchByIds", method = RequestMethod.POST)
    @ApiOperation(value = "根据Id查询对象列表", notes = "根据Id查询对象列表")
    public List queryBatchByIds(@RequestBody List<String> ids) {
        List list = formTaskService.getBatchByIds(ids);
        return list;
    }

    @RequestMapping(value = "/queryPage", method = RequestMethod.GET)
    @ApiOperation(value = "模板分页查询", notes = "模板分页查询")
    public IPage<FormTaskEntity> queryPage(FormTaskEntity formTaskEntity, Integer currentPage, Integer pageSize) {
        if (currentPage == null) {
            currentPage = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        injectCheckDataAuth(formTaskEntity);
        IPage<FormTaskEntity> pageBean = formTaskService.getPage(formTaskEntity, currentPage, pageSize);
        List<FormTaskEntity> list = pageBean.getRecords();
        if (BeanUtil.isNotEmpty(list) && list.size() > 0) {

            // 数据源id集合
            List<String> databaseIdList = list.stream().map(FormTaskEntity::getViewId).distinct().collect(Collectors.toList());
            // 数据源信息集合
            List<FormViewPubEntity> databaseList = formViewPubService.listByIds(databaseIdList);
            // 数据源信息集合-map
            Map<String, String> formViewPubMap = databaseList.stream().collect(Collectors.toMap(FormViewPubEntity::getId, FormViewPubEntity::getName));

            // 用户id集合
            List<String> idsList = list.stream().map(FormTaskEntity::getCreateId).distinct().collect(Collectors.toList());
            // 用户信息集合
            List<UcUserEntity> userList = ucUserService.queryByIds(idsList);
            // 用户信息集合-map
            Map<String, String> userMap = userList.stream().collect(Collectors.toMap(UcUserEntity::getId, UcUserEntity::getUserName));

            // 数据填充
            for (FormTaskEntity taskEntity : list) {
                taskEntity.setViewName(formViewPubMap.get(taskEntity.getViewId()));
                taskEntity.setCreateName(userMap.get(taskEntity.getCreateId()));
            }
        }
        return pageBean;
    }

    @RequestMapping(value = "/queryList", method = RequestMethod.GET)
    @ApiOperation(value = "模板查询", notes = "模板查询")
    public List queryList(FormTaskEntity formTaskEntity) {
        injectCheckDataAuth(formTaskEntity);
        List list = formTaskService.getList(formTaskEntity);
        return list;
    }
}